﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using System.ComponentModel;
using System.Messaging;

namespace Argos.Activities.MessageDelivery
{
	/// <summary>
	/// A message delivery activity that writes the message to a message queue.
	/// </summary>
	public class MessageQueueDeliveryActivity : MessageDeliveryActivityBase
	{

		#region #ctor: public MessageQueueDeliveryActivity()

		/// <summary>
		/// Creates a new instance of the class.
		/// </summary>
		public MessageQueueDeliveryActivity()
		{
			this.MessageLabel = "Argos Alert";
		}

		#endregion
		
		
		
		#region public string MessageLabel { get; set; }

		public static readonly DependencyProperty MessageLabelProperty = DependencyProperty.Register("MessageLabel", typeof(string), typeof(MessageQueueDeliveryActivity));

		[Category("Messaging")]
		[DisplayName("Message Label")]
		[Description("Specifies the message queue label that will be applied to the message written to the queue.")]
		public string MessageLabel
		{
			get { return (string)this.GetValue(MessageLabelProperty); }
			set { this.SetValue(MessageLabelProperty, value); }
		}

		#endregion
		
		#region public string Path { get; set; }

		public static readonly DependencyProperty PathProperty = DependencyProperty.Register("Path", typeof(string), typeof(MessageQueueDeliveryActivity));

		/// <summary>
		/// Sets or returns the path to the message queue to write the message to.
		/// </summary>
		[Category("Messaging")]
		[Description("Specifies the path to the queue to which this activity should write the message.")]
		public string Path
		{
			get { return (string)this.GetValue(PathProperty); }
			set { this.SetValue(PathProperty, value); }
		}

		#endregion



		#region protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)

		/// <summary>
		/// Writes the message to the message queue specified in <see cref="Path"/>.
		/// </summary>
		protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
		{
			using (MessageQueue que = new MessageQueue(this.Path))
			{
				// Don't need to serialize the message to an XML string because the queue
				// seems to use XML serialization to serialize the message to the queue
				// anyway.
				// This way, the alert message is serialized to the queue as an XML document
				// and not as a string.
				que.Send(this.Message, this.MessageLabel);
			}

			return ActivityExecutionStatus.Closed;
		}

		#endregion

	}
}
